import configparser
import logging

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from flask_apscheduler import APScheduler
from camera.service import save_daily_camera_data

# 获取日志记录器
logger = logging.getLogger(__name__)

def get_scheduler_time():
    """
    从config.ini中读取定时任务时间
    :return: 定时任务时间字符串，格式为"HH:MM"
    """
    config = configparser.ConfigParser()
    config.read('config/config.ini', encoding='utf-8')
    return config.get('scheduler', 'time', fallback='23:59:30')


def configure_scheduler(app):
    """
    配置定时任务调度器
    """
    scheduler = APScheduler()
    scheduler.init_app(app)

    # 获取定时任务时间
    scheduled_time = get_scheduler_time()
    hour, minute, second = map(int, scheduled_time.split(":"))
    # 添加定时任务，并确保在应用上下文中运行
    def wrapped_save_daily_camera_data():
        with app.app_context():  # 手动激活应用上下文
            save_daily_camera_data()
    # 添加定时任务
    scheduler.add_job(id='save_daily_camera_data',
                      func=wrapped_save_daily_camera_data,
                      trigger='cron',
                      hour=hour,
                      minute=minute,
                      second=second)
    scheduler.start()
    logger.info(f"定时任务已启动，每天 {scheduled_time}")

def start_scheduler():
    """
    启动定时任务调度器
    """
    scheduler = BackgroundScheduler()

    # 获取定时任务时间
    scheduled_time = get_scheduler_time()
    hour, minute, second = map(int, scheduled_time.split(":"))

    # 添加定时任务
    trigger = CronTrigger(hour=hour, minute=minute, second=second)
    scheduler.add_job(save_daily_camera_data, trigger)
    scheduler.start()
    logger.info(f"定时任务已启动，每天 {scheduled_time} 执行数据保存任务")
